# -*- coding:utf-8 -*-
import MySQLdb
from mycoolpai.initclass import CPConf

class MySQL:
    '''管理mysql的类'''
    def __init__(self):
        myconf = CPConf()
        self.hostip = myconf.getValue('dbhostip')
        self.user = myconf.getValue('dbuser')
        self.passwd = myconf.getValue('dbpasswd')
        self.dbname = myconf.getValue('dbname')
    
    def connectdb(self):
        '''
        @return: True表示连接数据库成功
                False表示连接失败
        '''
        try:
            self.conn = MySQLdb.connect(host=self.hostip,user=self.user,passwd=self.passwd,db=self.dbname)
            self.cursor = self.conn.cursor()
            return True
        except Exception,e:
            return False
        
    def close(self):
        self.cursor.close()
        self.conn.close()
        
    def user_register(self,email,password,nickname):
        '''
        @param email: 用户email
        @param password: 密码
        @param nickname: 用户昵称
        @return: (True,'')表示注册成功
                (False,info)表示注册失败，info字符串是失败原因提示
        '''
        try:
            sql = 'insert into user(email,password,nickname) values("%s","%s","%s")'%(email,password,nickname)
            n=self.cursor.execute(sql)
            self.conn.commit()
            if n>0:
                return True,''
            else:
                return False,'该Email已经注册过'
        except Exception,e:
            print e
            info = '暂停注册服务'
            if e[0] == 1062:
                info = '该Email已注册'
            return False,info
    
    def check_user_availability(self,field,value):
        '''
        @param field: 用户需要检查的字段
        @param value: 字段值
        @return: True表示已查到；False表示未查到或查询出现了异常
        '''
        try:
            sql = 'select * from user where %s="%s"'%(field,value)
            n = self.cursor.execute(sql)
            self.conn.commit()
            if n>0:
                return True
            else:
                return False
        except Exception,e:
            #这个地方要记录日志
            print e
            return False